package com.hairline.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hairline.aspect.AdminOperationLog;
import com.hairline.bean.*;
import com.hairline.bean.vo.BaseRespVo;
import com.hairline.bean.vo.DashBoardVo;
import com.hairline.bean.vo.UserManagementVO;
import com.hairline.mapper.*;
import com.hairline.service.UserService;
import com.hairline.shiro.MallToken;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.session.Session;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import java.io.Serializable;
import java.lang.System;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@SuppressWarnings("ALL")
public class AuthController {


    @Autowired
    UserService userServiceImpl;
    @PostMapping("admin/auth/login")
    @AdminOperationLog
    public BaseRespVo login(@RequestBody Map map){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        Subject subject = SecurityUtils.getSubject();

        try{
        subject.login(new MallToken(username,password,"adminrealm"));
        }
        catch (Exception e){

            return BaseRespVo.fail("登陆失败");
        }


        Session session = subject.getSession();
        session.setAttribute("username",username);
        Serializable id = session.getId();
        return BaseRespVo.ok(id);
    }



    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AdminMapper adminMapper;

    @RequestMapping("admin/auth/info")
    public BaseRespVo info(String token,HttpServletRequest request){
        InfoData infoData = new InfoData();
        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");


        Subject subject = SecurityUtils.getSubject();
        String primaryPrincipal1 = (String) subject.getPrincipals().getPrimaryPrincipal();


        String username=primaryPrincipal1;
        infoData.setName(username);
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);

        //查询该用户拥有的角色名
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        Integer[] roleIds = admins.get(0).getRoleIds();


        ArrayList<String> roleNames = new ArrayList<>();
        for (Integer roleId : roleIds) {
            Role role = roleMapper.selectByPrimaryKey(roleId);
            roleNames.add(role.getName());
        }

        infoData.setRoles(roleNames);
        return BaseRespVo.ok(infoData);
    }

    /**
     * 首页
     * @return
     */
//    TODO
    @Autowired
    UserMapper userMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper productMapper;
    @Autowired
    OrderMapper orderMapper;
    @RequestMapping("admin/dashboard")
    public BaseRespVo dashboard(){

        DashBoardVo dashBoardVo = new DashBoardVo();
        dashBoardVo.setGoodsTotal(goodsMapper.count());
        dashBoardVo.setOrderTotal(orderMapper.count());
        dashBoardVo.setProductTotal(productMapper.count());
        dashBoardVo.setUserTotal(userMapper.count());
        return BaseRespVo.ok(dashBoardVo);
    }

    /**
     * 登出
     */
    @AdminOperationLog
    @RequestMapping("admin/auth/logout")
    public BaseRespVo logout(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return BaseRespVo.ok();
    }

    /**
     * 会员管理
     */
    @RequestMapping("/admin/user/list")
    public BaseRespVo userManagement(@RequestParam("page") Integer page,
                                         @RequestParam("limit") Integer limit,
                                         @RequestParam(value = "username",required = false) String username,
                                         @RequestParam(value = "mobile",required = false) String mobile,
                                         @RequestParam("sort") String addTime,
                                         @RequestParam("order") String order) {
        if (username == null) username = "";
        if (mobile == null) mobile = "";
        List<User> users = userServiceImpl.queryAllUserInfo(page,limit,username,mobile,addTime,order);

        UserManagementVO userManagementVO = getUserManagementVO(page, limit, users);
        return BaseRespVo.ok(userManagementVO);


    }

    private UserManagementVO getUserManagementVO(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, List list) {
        //开启分页
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();

        UserManagementVO userManagementVO = new UserManagementVO();
        userManagementVO.setTotal(total);
        userManagementVO.setItems(list);
        return userManagementVO;
    }

    /**
     *收货地址
     * @param page
     * @param limit
     * @param name
     * @param userId
     * @param addTime
     * @param order
     * @return
     */
    @RequestMapping("/admin/address/list")
    public BaseRespVo queryReceiveAddress(@RequestParam("page") Integer page,
                                              @RequestParam("limit") Integer limit,
                                              @RequestParam(value = "name",required = false) String name,
                                              @RequestParam(value = "userId",required = false) String userId,
                                              @RequestParam("sort") String addTime,
                                              @RequestParam("order") String order) {

        if (name == null) name = "";
        List<Address> addresses = userServiceImpl.queryAllReceiveAddress(page,limit,name,userId,addTime,order);


        UserManagementVO userManagementVO = getUserManagementVO(page, limit, addresses);
        return BaseRespVo.ok(userManagementVO);
    }

    /**
     * 会员收藏
     * @param page
     * @param limit
     * @param valueId
     * @param userId
     * @param addTime
     * @param order
     * @return
     */
    @RequestMapping("/admin/collect/list")
    public BaseRespVo queryAllUserCollections(@RequestParam("page") Integer page,
                                                  @RequestParam("limit") Integer limit,
                                                  @RequestParam(value = "valueId",required = false) String valueId,
                                                  @RequestParam(value = "userId",required = false) String userId,
                                                  @RequestParam("sort") String addTime,
                                                  @RequestParam("order") String order) {

        if (valueId == null) valueId = "";
        if (userId == null) userId = "";

        List<Collect> collects = userServiceImpl.queryAllUserCollections(page, limit, valueId, userId, addTime, order);

        UserManagementVO userManagementVO = getUserManagementVO(page, limit, collects);
        return BaseRespVo.ok(userManagementVO);
    }

    /**
     * 会员足迹
     * @param page
     * @param limit
     * @param goodsId
     * @param userId
     * @param addTime
     * @param order
     * @return
     */
    @RequestMapping("/admin/footprint/list")
    public BaseRespVo queryAllUserFootprint(@RequestParam("page") Integer page,
                                                @RequestParam("limit") Integer limit,
                                                @RequestParam(value = "goodsId",required = false) String goodsId,
                                                @RequestParam(value = "userId",required = false) String userId,
                                                @RequestParam("sort") String addTime,
                                                @RequestParam("order") String order) {

        if (goodsId == null) goodsId = "";
        if (userId == null) userId = "";

        List<Footprint> footprints = userServiceImpl.queryAllFootprint(page, limit, goodsId, userId, addTime, order);

        UserManagementVO userManagementVO = getUserManagementVO(page, limit, footprints);
        return BaseRespVo.ok(userManagementVO);
    }

    /**
     * 搜索历史
     * @param page
     * @param limit
     * @param keyword
     * @param userId
     * @param addTime
     * @param order
     * @return
     */
    @RequestMapping("/admin/history/list")
    public BaseRespVo queryAllUserSearchHistory(@RequestParam("page") Integer page,
                                                    @RequestParam("limit") Integer limit,
                                                    @RequestParam(value = "keyword",required = false) String keyword,
                                                    @RequestParam(value = "userId",required = false) String userId,
                                                    @RequestParam("sort") String addTime,
                                                    @RequestParam("order") String order) {

        if (keyword == null) keyword = "";
        if (userId == null) userId = "";

        List<SearchHistory> searchHistories = userServiceImpl.queryAllUserSearchHistory(page, limit, keyword, userId, addTime, order);

        UserManagementVO userManagementVO = getUserManagementVO(page, limit, searchHistories);
        return BaseRespVo.ok(userManagementVO);
    }




    /**
     * 意见反馈
     * @param page
     * @param limit
     * @param username
     * @param id
     * @param addTime
     * @param order
     * @return
     */
    @RequestMapping("/admin/feedback/list")
    public BaseRespVo queryAllUserFeedback(@RequestParam("page") Integer page,
                                               @RequestParam("limit") Integer limit,
                                               @RequestParam(value = "username",required = false) String username,
                                               @RequestParam(value = "id",required = false) String id,
                                               @RequestParam("sort") String addTime,
                                               @RequestParam("order") String order) {

        if (username == null) username = "";
        if (id == null) id = "";

        List<Feedback> feedbacks = userServiceImpl.queryAllUserFeedBack(page, limit, username, id, addTime, order);

        UserManagementVO userManagementVO = getUserManagementVO(page, limit, feedbacks);
        return BaseRespVo.ok(userManagementVO);
    }

    //未经认证就访问的情况处理

}
